package net.dgg.rz.api.production.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.dgg.framework.tac.utils.bean.DggRestResponse;
import net.dgg.framework.tac.utils.web.commmon.DggBaseController;
import net.dgg.iboss.base.entity.uc.CustomerDTO;
import net.dgg.iboss.base.service.CmsService;
import net.dgg.iboss.base.service.UcApiService;
import net.dgg.iboss.base.util.CustomerNumberEncryptionUtil;
import net.dgg.iboss.base.util.DesUtil;
import net.dgg.iboss.base.util.JsonUtil;
import net.dgg.rz.api.production.service.ApiProductionService;
import net.dgg.rz.common.constant.ScProductConstant;
import net.dgg.rz.common.excption.CommonExcption;
import net.dgg.rz.common.utils.StringUtils;
import net.dgg.rz.common.utils.UniqueOrderUtils;
import net.dgg.rz.common.utils.ValidateUtils;
import net.dgg.rz.production.entity.*;
import net.dgg.rz.production.service.FlowNodeService;
import net.dgg.rz.production.service.OrderJsonService;
import net.dgg.tmd.foundation.platform.common.util.TranslateUtil;
import net.dgg.tmd.foundation.platform.treebook.entity.TreeBook;
import net.dgg.tmd.foundation.platform.treebook.service.TreeBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>@Title 生产部分对外接口controller</p>
 * <p>@Version 1.0.0 版本号</p>
 * <p>@author zyou</p>
 * <p>@date 2018年12月25日</p>
 * <p>Copyright © dgg group.All Rights Reserved. 版权信息</p>
 */
@SuppressWarnings("ALL")
@Controller
@RequestMapping("/rzsc/api")
@Api(description = "生产给IBOSS提供的接口")
public class ApiOutController extends DggBaseController {

    @Autowired
    private FlowNodeService flowNodeService;
    @Autowired
    private ApiProductionService apiProductionService;

    @Autowired
    private OrderJsonService orderJsonService;
    @Autowired
    private UcApiService ucApiService;
    @Autowired
    private CmsService cmsService;
    @Autowired
    private DesUtil desUtil;
    @Autowired
    private TranslateUtil translateUtil;
    @Autowired
    UniqueOrderUtils uniqueOrderUtils;

    @Value("${rzscUnderOrderUrl}")
    private String rzscUnderOrderUrl;

    @Resource
    private TreeBookService treeBookService;

    /**
     * <p>@Description IBOSS第一次调用接口</p>
     * <p>@author mqy</p>
     * <p>@Time 2018/11/23 0023 11:58 创建时间</p>
     * <p>@return</p>
     */
    @ResponseBody
    @RequestMapping("/inset_order_temp")
    public DggRestResponse insetOrderTemp(String returnUrl,String notifyUrl,String order,String products){
        try{
            //保存一条数据
            String orderNo = orderJsonService.saveOrderJson(returnUrl,notifyUrl,order,products);
            Map data = new HashMap<String,Object>(){{put("redirect",rzscUnderOrderUrl+"?orderNo="+orderNo);}};
            return this.getSuccessResponse(data);
        }catch (CommonExcption e){
            e.printStackTrace();
            return this.getFailResponse(e.getMessage());
        }
    }

    /**
     * <p>@Description IBOSS调用查询接口</p>
     * <p>@author mqy</p>
     * <p>@Time 2018/11/23 0023 13:40 创建时间</p>
     * <p>@return</p>
     */
    @ResponseBody
    @RequestMapping("query_order_temp")
    public DggRestResponse queryOrderTemp(@RequestParam Map params) {

        try {
            OrderJson orderJson = orderJsonService.selectByOrderId(Long.parseLong(params.get("orderId").toString()));
            Map data = new HashMap<String, Object>();
            if(null != orderJson && orderJson.getFlag() == 0){
                data.put("status", "ORF_DDZT_ORDER_OK");
            }else{
                data.put("status", "ORF_DDZT_ORDER_ERROR");
            }
            return this.getSuccessResponse(data);
        }catch (Exception e){
            e.printStackTrace();
            return this.getFailResponse("下单失败");
        }

    }


    @RequestMapping("/under_order")
    public String underOrder(Model model, String orderNo){
        OrderJson orderJson = orderJsonService.selectByOrderNo(orderNo);
        Map orderMap = JsonUtil.json2Obj(orderJson.getOrderJson(),Map.class);
        String[] hideColum = {"contactPhone"};
        String contactPhone = desUtil.decrypt(String.valueOf(orderMap.get("contactPhone")));//解密电话号码
        orderMap.put("contactPhone",contactPhone);
        orderMap = CustomerNumberEncryptionUtil.encryptionObject(hideColum, orderMap);
        model.addAttribute("order", orderMap);
        model.addAttribute("products",JsonUtil.json2List(orderJson.getOrderBusinessJson(),Map.class));
        model.addAttribute("customerPhone",orderMap.get("customerPhone")==null?"":orderMap.get("customerPhone").toString());

        //查询客户信息过来
        CustomerDTO customerDTO = ucApiService.findCustomerById(Long.parseLong(orderMap.get("customerId").toString()));
        model.addAttribute("customerDTO", customerDTO);

        return "rzsc/underorder/under_order";
    }

    /**
     * 提交审核
     * @param params
     * @return
     */
    @RequestMapping("/save_under_order")
    @ResponseBody
    public DggRestResponse saveUnderOrder(@RequestParam Map params){
        try {
            //先保存json数据（首先验证是否已经生成生产订单）
            ValidateUtils.strNotEmpty(params.get("orderNo"),CommonExcption.class,"订单编号为空");
            String orderNo = params.get("orderNo").toString();
            String businessJsonArr=params.get("businessJsonArr").toString();
            boolean res= uniqueOrderUtils.uniqueOrder(businessJsonArr);
            if (res) {
                ValidateUtils.isTrue(!res, CommonExcption.class, "产品品+渠道不唯一，请核查后再试");
            }
            OrderJson orderJson = apiProductionService.findOrderJsonByOrderNo(orderNo);
            if(null != orderJson){
                if(orderJson.getFlag() != 1){
                    apiProductionService.updateOrderJson(orderJson,params,2);//只会进这里
                    return this.getSuccessResponse(orderJson.getReturnUrl());
                }else{
                    return this.getFailResponse("当前订单已经生成生产单，请勿重复下单！");
                }
            }else {
                apiProductionService.updateOrderJson(orderJson,params,1);
                return this.getSuccessResponse("提交成功");
            }
        }catch (CommonExcption e){
            e.printStackTrace();
            return this.getFailResponse(e.getMessage());
        }catch (Exception e){
            e.printStackTrace();
            return this.getFailResponse(e.getMessage());
        }
    }


    /**
     * 审核通过生成生产单
     * @return
     */
    @RequestMapping("/create_product_order")
    @ResponseBody
    public DggRestResponse createProductOrder(String order){
        try {
            //先保存json数据（首先验证是否已经生成生产订单）
            Map orderMap = JsonUtil.json2Obj(order,Map.class);
            String orderNo = orderMap.get("orderNo").toString();
            OrderJson orderJson = apiProductionService.findOrderJsonByOrderNo(orderNo);
            if(null != orderJson){
                if(orderJson.getFlag() != 1){
                    apiProductionService.createProductOrder(orderJson,order);
                    return this.getSuccessResponse("提交成功");
                }else{
                    return this.getFailResponse("当前订单已经生成生产单，请勿重复下单！");
                }
            }else {
                return this.getFailResponse("生成生产订单异常！");
            }
        }catch (CommonExcption e){
            e.printStackTrace();
            return this.getFailResponse(e.getMessage());
        }
    }


    /**
     * 查询业务底单页面
     * @param model
     * @param orderNo
     * @return
     */
    @RequestMapping("/query_under_order")
    public String queryUnderOrder(Model model, String orderNo){
        OrderJson orderJson = orderJsonService.selectByOrderNo(orderNo);
        if(orderJson==null){
            return "rzsc/underorder/query_under_order";
        }
        Map orderMap = JsonUtil.json2Obj(orderJson.getOrderJson(),Map.class);
        String[] hideColum = {"contactPhone"};
        String contactPhone = desUtil.decrypt(String.valueOf(orderMap.get("contactPhone")));//解密电话号码
        orderMap.put("contactPhone",contactPhone);
        orderMap = CustomerNumberEncryptionUtil.encryptionObject(hideColum, orderMap);
        String[] transColumOrderJson = {"loansRateType"};
        model.addAttribute("orderJson",translateUtil.translateObject(transColumOrderJson, orderJson));
        model.addAttribute("order", orderMap);
        String[] transColumProducts = {"rateType"};
        List<Map> products = JsonUtil.json2List(orderJson.getOrderBusinessJson(),Map.class);
        products = translateUtil.translateList(transColumProducts, products);
        if(products != null && products.size()>0){
            for(Map map:products){
                if(StringUtils.isEmpty(map.get("flowUserName"))&&!StringUtils.isEmpty(map.get("flowUserId"))){
                    Map userMap = cmsService.findUser(Long.parseLong(map.get("flowUserId").toString()));
                    if (null != userMap) {
                        String realName = userMap.get("realName")==null?"":userMap.get("realName").toString();
                        String loginName = userMap.get("loginName")==null?"":userMap.get("loginName").toString();
                        map.put("flowUserName",realName+loginName);
                    }
                }
            }
        }
        model.addAttribute("products",products);
        //翻译字段
        String[] transColumCustomer = {"sex", "eduBackground", "maritalStatus"};
        Map customerDTO = orderJson.getCustomerJson()==null?null:JsonUtil.json2Obj(orderJson.getCustomerJson(),Map.class);
        customerDTO = translateUtil.translateObject(transColumCustomer, customerDTO);
        model.addAttribute("customerDTO", customerDTO);

        String[] transColumContact = {"contactMaritalStatus", "relationshipOfCus"};
        String[] hideColumContact = {"no"};
        List<Map> contactDTO = orderJson.getContactJson()==null?null:JsonUtil.json2List(orderJson.getContactJson(),Map.class);
        contactDTO = translateUtil.translateList(transColumContact, contactDTO);
        contactDTO = desUtil.decryptListMap(hideColumContact,contactDTO);//解密电话号码
        contactDTO = CustomerNumberEncryptionUtil.encryptionList(hideColumContact, contactDTO);
        model.addAttribute("contactDTO",contactDTO);

        String[] transColumSubject = {"subjectType"};
        List<Map> subjectDTO = orderJson.getSubjectJson()==null?null:JsonUtil.json2List(orderJson.getSubjectJson(),Map.class);
        subjectDTO = translateUtil.translateList(transColumSubject, subjectDTO);
        model.addAttribute("subjectDTO", subjectDTO);

        return "rzsc/underorder/query_under_order";
    }


    /**
     * 兼容呱呱云产品
     * 获取流程配置信息
     * @return
     */
    @RequestMapping(value = "/insert_process_config.do")
    @ResponseBody
    public DggRestResponse insertProcessConfig(){
        try{
            flowNodeService.insertProcessConfig();
            return this.getSuccessResponse("成功");
        }catch (CommonExcption e){
            e.printStackTrace();
            return this.getFailResponse(e.getMessage());
        }catch (Exception e) {
            e.printStackTrace();
            return this.getFailResponse(e.getMessage());
        }
    }

    /**
     * iBoss接收企大宝订单
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/inset_order_all.do", method = RequestMethod.POST)
    public DggRestResponse insertOrderAll(@Validated @RequestBody QdsScOrderVo qdsScOrderVo){
        try{
            logger.info("接收企大宝订单开始：" + JsonUtil.obj2Json(qdsScOrderVo));
            Long flowerId = qdsScOrderVo.getFlowerId();
            if(StringUtils.isEmpty(flowerId)){
                return this.getFailResponse("流程人员不能为空");
            }
            TreeBook treeBook = treeBookService.getTreeBookByCode("RZSC_SC_BUS_YT");
            if(net.dgg.iboss.base.util.StringUtils.isEmptyObj(treeBook)){
                return this.getFailResponse("融资生产未查询到数据字典");
            }
            if(net.dgg.iboss.base.util.StringUtils.isEmpty(treeBook.getExt1())){
                return this.getFailResponse("融资生产数据字典未配置可分单业态");
            }
            if(!treeBook.getExt1().contains(qdsScOrderVo.getOrderVo().getBusinessTypeNo())){
                return this.getFailResponse("融资生产暂不支持" + qdsScOrderVo.getOrderVo().getBusinessTypeName()  +"业态订单");
            }
            apiProductionService.allotScOrder(qdsScOrderVo);
            return this.getSuccessResponse("保存成功");
        }catch (CommonExcption e){
            e.printStackTrace();
            logger.info(e.getMessage());
            return this.getFailResponse(e.getMessage());
        }catch (Exception e){
            e.printStackTrace();
            logger.error(e.getMessage());
            return this.getFailResponse("操作失败，请联系管理员！");
        }
    }

    /**
     * @Title:
     * @Description: TODO 根据生产订单ID查询当前节点，最新更新时间，办理人
     * @param:
     * @return:
     * @throw:
     * @author: sdx
     * @creat_date: 2019/8/26
     **/
    @ResponseBody
    @RequestMapping(value = "v1/get_product_order_by_id.do", method = RequestMethod.POST)
    @ApiOperation(value = "根据生产订单ID查询当前节点，最新更新时间，办理人", notes = "根据生产订单ID查询当前节点，最新更新时间，办理人", httpMethod = "POST")
    public DggRestResponse getProductOrderById(@Validated @RequestBody NodeOperateRecordCondition nodeOperateRecordCondition) {
        try {
            logger.info("查询节点记录开始---------》"+ JsonUtil.obj2Json(nodeOperateRecordCondition));
            if (null != nodeOperateRecordCondition) {
                Map params = new HashMap<>();
                params.put("scProductOrderId", nodeOperateRecordCondition.getScOrderId());
                List<Map<String, Object>> list = apiProductionService.getProductOrderById(params);
                return this.buildResponse(200,"请求成功！",list);
            } else {
                return this.getFailResponse("接收对象参数不能为空！");
            }
        } catch (Exception e) {
            return this.getFailResponse("操作失败：" + e.getMessage());
        }
    }

    /**
     * @Title:
     * @Description: TODO 根据生产订单ID查询生产订单ID，任务ID，节点ID，任务名称，节点名称，最新更新时间，办理人,备注
     * @param:
     * @return:
     * @throw:
     * @author: sdx
     * @creat_date: 2019/8/26
     **/
    @ResponseBody
    @RequestMapping(value = "v1/get_product_node_by_id.do", method = RequestMethod.POST)
    @ApiOperation(value = "根据生产订单ID查询生产订单ID，任务ID，节点ID，任务名称，节点名称，最新更新时间，办理人,备注", notes = "根据生产订单ID查询生产订单ID，任务ID，节点ID，任务名称，节点名称，最新更新时间，办理人,备注", httpMethod = "POST")
    public DggRestResponse getProductNodeById(@Validated @RequestBody TaskOperateRecordPageCondition taskOperateRecordPageCondition) {
        try {
            logger.info("查询节点表开始---------》"+ JsonUtil.obj2Json(taskOperateRecordPageCondition));
            if (null != taskOperateRecordPageCondition) {
                Map params = new HashMap<>();
                params.put("scProductOrderId", taskOperateRecordPageCondition.getScOrderId());
                params.put("start", (taskOperateRecordPageCondition.getStart()-1) * taskOperateRecordPageCondition.getLimit());
                params.put("limit", taskOperateRecordPageCondition.getLimit());
                List<TaskOperateRecord> list = apiProductionService.getProductNodeById(params);
                PageList<TaskOperateRecord> pageList = new PageList<>();
                pageList.setRecords(list);
                pageList.setTotalCount(apiProductionService.count(params));
                pageList.setPageSize(taskOperateRecordPageCondition.getLimit());
                pageList.setCurrentPage(taskOperateRecordPageCondition.getStart());
                return this.buildResponse(200,"请求成功！",pageList);
            } else {
                return this.getFailResponse("接收对象参数不能为空！");
            }
        } catch (Exception e) {
            return this.getFailResponse("操作失败：" + e.getMessage());
        }
    }


    /**
     * 根据生产订单ID查询生产单服务团队
     * @param scOrderId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getScOrderManagementTeam.do", method = RequestMethod.GET)
    @ApiOperation(value = "根据生产订单ID查询生产单服务团队", notes = "根据生产订单ID查询生产单服务团队", httpMethod = "GET")
    public DggRestResponse getScOrderManagementTeam(String scOrderId) {
        try {
            if(StringUtils.isEmpty(scOrderId)){
                return super.getFailResponse("生产单id为空！");
            }
            List<Map> userMap = apiProductionService.getScOrderManagementTeam(scOrderId);
            return super.getSuccessResponse(userMap);
        } catch (Exception e) {
            return this.getFailResponse("操作失败：" + e.getMessage());
        }
    }
}
